package com.hooda.framework.factory;

import com.hooda.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;

/**
 * @author zhangzp
 * @version 1.0, 2021/9/9
 */
public class ProxyFactory {

    public static Object getJdkProxy(Object target) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return handle(method, target, args);
            }
        });
    }

    public static Object getCglibProxy(Object target) {
        return Enhancer.create(target.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                return handle(method, target, args);
            }
        });
    }

    private static Object handle(Method method, Object target, Object[] args) throws SQLException, InvocationTargetException, IllegalAccessException {
        Object result;

        try {

            TransactionManager.getInstance().beginTransaction();

            result = method.invoke(target, args);

            TransactionManager.getInstance().commit();
        } catch (Exception e) {
            e.printStackTrace();

            TransactionManager.getInstance().rollback();

            throw e;
        }

        return result;
    }
}
